import logging

from django.core.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.views import APIView

from drf_spectacular.utils import OpenApiExample, extend_schema
from app.services.franchise_service import FranchiseService
from middleware.util import AUTH_HEADER_PARAM

logger = logging.getLogger('app')


@extend_schema(
    tags=['加盟申请模块'],
    summary='提交加盟申请',
    description='普通用户提交商家加盟申请',
    parameters=[AUTH_HEADER_PARAM],
    request={
        'application/json': {
            'type': 'object',
            'properties': {
                'shop_name': {'type': 'string'},
                'location': {'type': 'string'},
                'contact_info': {'type': 'string'},
                'business_hours': {'type': 'string'},
                'introduction': {'type': 'string', 'nullable': True}
            },
            'required': ['shop_name', 'location', 'contact_info', 'business_hours']
        }
    },
    responses={
        201: {
            'description': '申请提交成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'object',
                    'properties': {
                        'application_id': {'type': 'string', 'format': 'uuid'},
                        'shop_name': {'type': 'string'},
                        'status': {'type': 'string'}
                    }
                }
            }
        },
        400: {'description': '参数错误或商家名已被申请'},
        403: {'description': '权限不足（需要普通用户身份）'}
    }
)
class SubmitFranchiseApplicationView(APIView):
    def post(self, request):
        try:
            # 从JWT token获取用户ID
            user_id = getattr(request, 'user_id', None)
            if not user_id:
                return Response({"code": 403, "message": "权限不足"}, status=403)

            data = request.data
            shop_name = data.get('shop_name')
            location = data.get('location')
            contact_info = data.get('contact_info')
            business_hours = data.get('business_hours')
            introduction = data.get('introduction')

            result = FranchiseService.submit_application(
                user_id=user_id,
                shop_name=shop_name,
                location=location,
                contact_info=contact_info,
                business_hours=business_hours,
                introduction=introduction
            )
            return result

        except ValidationError as e:
            logger.error(f"申请提交失败: {str(e)}", exc_info=True)
            return Response({"code": 400, "message": str(e)}, status=400)
        except Exception as e:
            logger.error(f"申请提交失败: {str(e)}", exc_info=True)
            return Response({
                "code": 500,
                "message": "系统错误，请稍后再试"
            }, status=500)



@extend_schema(
    tags=['加盟申请模块'],
    summary='获取加盟申请列表',
    description='管理员获取所有加盟申请列表',
    responses={
        200: {
            'description': '成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'array',
                    'items': {
                        'type': 'object',
                        'properties': {
                            'application_id': {'type': 'string', 'format': 'uuid'},
                            'applicant_name': {'type': 'string'},
                            'shop_name': {'type': 'string'},
                            'location': {'type': 'string'},
                            'contact_info': {'type': 'string'},
                            'business_hours': {'type': 'string'},
                            'introduction': {'type': 'string', 'nullable': True},
                            'status': {'type': 'string'},
                            'created_at': {'type': 'string', 'format': 'date-time'},
                            'approval_time': {'type': 'string', 'format': 'date-time', 'nullable': True},
                            'approval_notes': {'type': 'string', 'nullable': True}
                        }
                    }
                }
            }
        },
        403: {'description': '权限不足'}
    }
)
class ListFranchiseApplicationsView(APIView):
    def get(self, request):
        try:

            response = FranchiseService.list_applications()
            return response
        except Exception as e:
            return Response({"code": 500, "message": f"系统错误：{str(e)}"}, status=500)


@extend_schema(
    tags=['加盟申请模块'],
    summary='审批加盟申请',
    description='管理员审批加盟申请（通过/拒绝）',
    request={
        'application/json': {
            'type': 'object',
            'properties': {
                'action': {
                    'type': 'string',
                    'enum': ['approve', 'reject'],
                    'description': '审批动作：approve=通过，reject=拒绝'
                },
                'notes': {'type': 'string', 'nullable': True, 'description': '审批备注'}
            },
            'required': ['action']
        }
    },
    responses={
        200: {
            'description': '审批成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'object',
                    'properties': {
                        'application_id': {'type': 'string', 'format': 'uuid'},
                        'status': {'type': 'string'},
                        'merchant_id': {'type': 'string', 'format': 'uuid', 'nullable': True}
                    }
                }
            }
        },
        400: {'description': '参数错误或申请状态不允许审批'},
        404: {'description': '申请不存在'},
        403: {'description': '权限不足'}
    }
)
class ApproveFranchiseApplicationView(APIView):
    def post(self, request, application_id):
        try:
            data = request.data
            action = data.get('action')
            notes = data.get('notes')

            if action not in ['approve', 'reject']:
                return Response({"code": 400, "message": "无效的审批动作"}, status=400)

            result = FranchiseService.approve_application(
                application_id=application_id,
                action=action,
                notes=notes
            )
            return result

        except ValidationError as e:
            return Response({"code": 400, "message": str(e)}, status=400)
        except Exception as e:
            logger.error(f"审批处理失败: {str(e)}", exc_info=True)
            return Response({"code": 500, "message": f"系统错误：{str(e)}"}, status=500)


@extend_schema(
    tags=['加盟申请模块'],
    summary='查看我的加盟申请',
    description='用户查看自己提交的加盟申请状态',
    parameters=[AUTH_HEADER_PARAM],
    responses={
        200: {
            'description': '成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'array',
                    'items': {
                        'type': 'object',
                        'properties': {
                            'application_id': {'type': 'string', 'format': 'uuid'},
                            'shop_name': {'type': 'string'},
                            'location': {'type': 'string'},
                            'contact_info': {'type': 'string'},
                            'business_hours': {'type': 'string'},
                            'introduction': {'type': 'string', 'nullable': True},
                            'status': {'type': 'string'},
                            'created_at': {'type': 'string', 'format': 'date-time'},
                            'approval_time': {'type': 'string', 'format': 'date-time', 'nullable': True},
                            'approval_notes': {'type': 'string', 'nullable': True}
                        }
                    }
                }
            }
        },
        403: {'description': '权限不足'}
    }
)
class GetMyFranchiseApplicationsView(APIView):
    def get(self, request):
        try:
            user_id = getattr(request, 'user_id', None)
            if not user_id:
                return Response({"code": 403, "message": "权限不足"}, status=403)

            response = FranchiseService.get_my_applications(user_id)
            return response
        except Exception as e:
            return Response({"code": 500, "message": f"系统错误：{str(e)}"}, status=500)